<?php

namespace App\Library\Service;

use App\Library\Logic\AmountLogic;
use App\Library\Logic\PaymentMethodLogic;
use App\Library\Logic\UserAccountLogic;
use App\Library\Logic\WithdrawLogic;
use App\Library\Requests\Withdraw\WithdrawApplyRequest;
use App\Library\Requests\Withdraw\WithdrawPageRequest;
use Illuminate\Http\JsonResponse;

class WithdrawService extends BaseService
{
    /**
     *
     * @return WithdrawLogic
     *
     */
    private function logic(): WithdrawLogic
    {
        if (empty($this->logic)) $this->logic = new WithdrawLogic;
        return $this->logic;
    }

    public function paging(WithdrawPageRequest $request): JsonResponse
    {
        return success($this->logic()->paging($request));
    }

    public function tj(): JsonResponse
    {
        return success([
            'auditing_money' => $this->logic()->auditingMoney()
        ]);
    }

    /**
     *
     * @param WithdrawApplyRequest $request
     * @return JsonResponse
     *
     */
    public function apply(WithdrawApplyRequest $request): JsonResponse
    {
        if ($request->paymentMethodType === 3) $request->paymentMethodType = 'unipay';
        $paymentMethod = PaymentMethodLogic::findByWhere('key', $request->paymentMethodType);
        if (is_null($paymentMethod)) return fail(640);

        $userAccount = UserAccountLogic::findByWhere([
            'userId' => USERID,
            'paymentMethodId' => $paymentMethod->id,
        ]);

        if (is_null($userAccount)) return fail(634);
        else if (AmountLogic::balance() < (float)$request->amount) return fail(635);
        $fee = 0;
        $withdraw = WithdrawLogic::insertForModel([
            'userId' => USERID,
            'userAccountId' => $userAccount->id,
            'paymentMethodId' => $paymentMethod->id,
            'name' => $userAccount->name,
            'identity' => $userAccount->identity,
            'amount' => $request->amount,
            'bank_name' => $userAccount->nickname,
            'fee' => $fee,
            'config' => null,
        ]);

        AmountLogic::insertForModelOfLock([
            'title' => '提现',
            'amountType' => 'withdraw',
            'userId' => $withdraw->user_id,
            'objectId' => $withdraw->id,
            'type' => 'withdraw',
            'objectType' => 'withdraw',
            'amount' => bcsub(0, bcadd($withdraw->amount, $fee, 2), 2),
            'description' => '提现',
            'extend' => ['fee' => $fee],
        ]);

        return success();
    }
}
